const task1 = () => {
  console.log('这是任务1')
}
const task2 = () => {
  console.log('这是任务2')
  for(let i = 0; i<10000; i++) {
    document.createElement('div')
  }
  console.log('任务2执行完了')
  return ()=>{
    console.log('下次继续执行')
  }
}

const task3 = () => {
  console.log('这是任务3')
}

const queue = [
  task1,task2,task3
]

let deadline = 0
const threshold: number = 5

// Performance.now()
// 返回一个表示从性能测量时刻开始经过的毫秒数 DOMHighResTimeStamp

export const getTime = () => performance.now()

const flush = () => {
  console.log('lai l')
  let task, next
  deadline = getTime() + threshold // TODO: heuristic algorithm
  while ((task = queue.pop()) && !shouldYield()) {
    ;(next = task()) && queue.push(next) && schedule(next)
  }
}

// 判断一个fiber计算是否大于5毫秒
export const shouldYield = (): boolean => {
  // console.log('should')
  const pending = getTime() >= deadline // 现在经过的时间是否大于5毫秒
  postTask = task()
  return pending
}

const task = () => {
  const { port1, port2 } = new MessageChannel()
  port1.onmessage = flush
  return () => port2.postMessage(null)
}

let postTask = task()

const schedule = (task: any): void => {
  queue.push(task) && postTask()
}

schedule(()=>{
  console.log('回调的')
})

console.log('最后一行')